<template>
  <div id="app">
    <AppNavbar />

    <div class="candidate-list-container">
      <div class="header">
        <h1>应聘者列表</h1>
        <button class="back-btn" @click="goBack">返回岗位列表</button>
      </div>

      <!-- 状态筛选下拉框 -->
      <div class="filter-container">
        <label for="status-filter">投递状态：</label>
        <select id="status-filter" v-model="selectedStatus" @change="filterCandidates">
          <option value="">全部</option>
          <option value="interested">感兴趣</option>
          <option value="inappropriate">不合适</option>
          <option value="not_viewed">未查看</option>
        </select>
      </div>

      <div class="candidate-list">
        <div
          v-for="candidate in filteredCandidateList"
          :key="candidate.userId"
          class="candidate-item"
        >
          <!-- 左侧内容：头像和基本信息 -->
          <div class="candidate-left-content">
            <img
              :src="candidate.avatarPath"
              :alt="candidate.nickname"
              class="candidate-avatar"
              @error="handleImageError"
            />

            <div class="candidate-info">
              <!-- 昵称显示在最上方 -->
              <h2 class="candidate-name">{{ candidate.nickname }}</h2>

              <!-- 其他信息显示在昵称下方 -->
              <div class="candidate-details">
                <span class="candidate-age">{{ candidate.age }}岁</span>
                <span class="candidate-sex">{{ getSexText(candidate.sex) }}</span>
                <span class="candidate-time">投递时间: {{ formatCreateTime(candidate.createTime) }}</span>
                <span class="candidate-status" :class="`status-${candidate.status}`">
                  {{ getStatusText(candidate.status) }}
                </span>
              </div>
            </div>
          </div>

          <!-- 右侧按钮区域 -->
          <div class="candidate-right-content">
            <!-- 替换 candidate-actions 部分 -->
<div class="candidate-actions">
  <button
    v-if="candidate.status === 'interested'"
    class="chat-btn"
    @click="chatWithCandidate(candidate)"
    :disabled="loadingCandidateId === candidate.userId"
  >
    {{ loadingCandidateId === candidate.userId ? '处理中...' : '聊一聊' }}
  </button>
  <template v-else>
    <button
      v-if="candidate.status === 'not_viewed'"
      class="interested-btn"
      @click="markAsInterested(candidate)"
      :disabled="loadingCandidateId === candidate.userId"
    >
      {{ loadingCandidateId === candidate.userId ? '处理中...' : '感兴趣' }}
    </button>
    <button
      class="view-btn"
      @click="viewResume(candidate)"
    >
      查看简历
    </button>
  </template>
</div>
          </div>
        </div>

        <div v-if="filteredCandidateList.length === 0" class="empty-state">
          <p>暂无应聘者</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import AppNavbar from '../components/AppNavbar.vue'
import apiClient from '../utils/api.js'

export default {
  name: 'EmployerCandidateListView',
  components: {
    AppNavbar
  },
  setup () {
    const candidateList = ref([])
    const selectedStatus = ref('')
    const route = useRoute()
    const router = useRouter()
    const loadingCandidateId = ref(null)

    // 计算属性：根据筛选状态过滤后的候选人列表
    const filteredCandidateList = computed(() => {
      if (!selectedStatus.value) {
        return candidateList.value
      }
      return candidateList.value.filter(candidate => candidate.status === selectedStatus.value)
    })

    onMounted(() => {
      fetchCandidateList()
    })

    const fetchCandidateList = async () => {
      try {
        const positionId = route.params.positionId
        const response = await apiClient.get('/employer/getCandidateList', {
          params: {
            positionId: positionId,
            status: selectedStatus.value
          }
        })

        if (response.data.code === '200') {
          candidateList.value = response.data.data
        } else {
          console.error('获取应聘者列表失败:', response.data.msg)
        }
      } catch (error) {
        console.error('请求出错:', error)
      }
    }

    const filterCandidates = () => {
      // 过滤逻辑已在 computed 属性中实现
    }

    const getSexText = (sex) => {
      const sexMap = {
        man: '男',
        woman: '女'
      }
      return sexMap[sex] || '未知'
    }

    const getStatusText = (status) => {
      const statusMap = {
        interested: '感兴趣',
        inappropriate: '不合适',
        not_viewed: '未查看'
      }
      return statusMap[status] || '未知状态'
    }

    const formatCreateTime = (createTime) => {
      if (!createTime) return ''
      const date = new Date(createTime)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }

    const handleImageError = (e) => {
      e.target.src = 'https://my-web-project-test-https://photo.fanya.chaoxing.com/photo_80.jpg'
    }

    const goBack = () => {
      router.push('/employerJobList')
    }

    const markAsInterested = async (candidate) => {
      loadingCandidateId.value = candidate.userId
      try {
        // 添加联系人
        await apiClient.put('/employer/addContact', null, {
          params: {
            candidateId: candidate.userId
          }
        })

        // 更新投递状态为感兴趣
        const statusResponse = await apiClient.post('/employer/updateDeliveryStatus', {
          userId: candidate.userId,
          positionId: route.params.positionId,
          status: 'interested'
        })

        if (statusResponse.data.code === '200') {
          // 更新本地状态
          candidate.status = 'interested'
        } else {
          console.error('更新状态失败:', statusResponse.data.msg)
        }
      } catch (error) {
        console.error('请求出错:', error)
      } finally {
        loadingCandidateId.value = null
      }
    }

    const chatWithCandidate = (candidate) => {
      router.push({
        path: '/chat',
        query: {
          contactId: candidate.userId.toString()
        }
      })
    }

    const viewResume = (candidate) => {
      router.push({
        name: 'CandidateVitae',
        query: {
          candidateId: candidate.userId,
          status: candidate.status,
          positionId: route.params.positionId
        }
      })
    }

    return {
      candidateList,
      filteredCandidateList,
      selectedStatus,
      loadingCandidateId,
      getSexText,
      getStatusText,
      formatCreateTime,
      handleImageError,
      goBack,
      filterCandidates,
      markAsInterested,
      chatWithCandidate,
      viewResume
    }
  }
}
</script>

<style scoped>
#app {
  background: linear-gradient(to right, #e0f7fa, #ffffff);
  min-height: 100vh;
  padding: 20px;
}

.candidate-list-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.header h1 {
  color: #1890ff;
  margin: 0;
}

.back-btn {
  background-color: #1890ff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.back-btn:hover {
  background-color: #40a9ff;
}

.filter-container {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.filter-container label {
  margin-right: 10px;
  font-weight: bold;
}

.filter-container select {
  padding: 8px 12px;
  border-radius: 4px;
  border: 1px solid #d9d9d9;
  background-color: white;
}

.candidate-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.candidate-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: white;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s;
}

.candidate-item:hover {
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.2);
}

.candidate-left-content {
  display: flex;
  align-items: flex-start; /* 改为flex-start对齐顶部 */
  flex-grow: 1;
  margin-right: 20px;
}

.candidate-avatar {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 20px;
  border: 2px solid #e8e8e8;
}

.candidate-info {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.candidate-name {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 500;
  align-self: flex-start; /* 确保昵称左对齐 */
}

.candidate-details {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  font-size: 14px;
  color: #666;
}

.candidate-age, .candidate-sex, .candidate-time, .candidate-status {
  font-size: 14px;
  color: #666;
}

.candidate-status.status-interested {
  color: #52c41a;
  font-weight: bold;
}

.candidate-status.status-inappropriate {
  color: #ff4d4f;
  font-weight: bold;
}

.candidate-status.status-not_viewed {
  color: #faad14;
  font-weight: bold;
}

.candidate-right-content {
  display: flex;
  align-items: center;
}

.candidate-actions {
  display: flex;
  gap: 10px;
}

.chat-btn {
  background-color: #52c41a;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.chat-btn:hover:not(:disabled) {
  background-color: #73d13d;
}

.chat-btn:disabled {
  background-color: #bfbfbf;
  cursor: not-allowed;
}

.view-btn {
  background-color: #1890ff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.view-btn:hover {
  background-color: #40a9ff;
}

.candidate-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: flex-end;
}

.tag {
  background-color: #e6f7ff;
  color: #1890ff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.empty-state {
  text-align: center;
  padding: 40px;
  background: white;
  border-radius: 8px;
  color: #999;
}
</style>
